package com.guoqi.marrydate

import android.os.Bundle
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.AppCompatImageView
import android.view.Gravity
import android.view.Menu
import android.view.MenuItem
import android.view.ViewGroup
import android.widget.Toast
import cn.aigestudio.datepicker.cons.DPMode
import cn.aigestudio.datepicker.views.DatePicker
import com.guoqi.marrydate.flag.FlagBean
import com.guoqi.marrydate.fm.FlagFm
import kotlinx.android.synthetic.main.activity_detail.*
import org.litepal.LitePal
import org.litepal.crud.callback.FindCallback
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*


class DetailActivity : AppCompatActivity() {

    val sdf = SimpleDateFormat("yyyy-MM-dd")//小写的mm表示的是分钟
    var id: Long = -1
    var title: String = "立个FLAG"
    var imgRes = R.mipmap.ic_goal
    var countType = 0 //0 倒计时 1正计时
    var weekPos = -1
    var monthPos = -1
    private lateinit var bean: FlagBean

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_detail)

        intent.getStringExtra("title")?.let {
            title = it
        }
        intent.getLongExtra("id", -1)?.let {
            id = it
            if (id > -1) {
                getById()
            }
        }
        intent.getSerializableExtra("bean")?.let {
            bean = it as FlagBean
            setData(bean)
        }

        toolbar.title = title
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setHomeButtonEnabled(true)

        tv_date.setOnClickListener {
            picker()
        }
        iv_goal.setOnClickListener {
            selectNone(iv_goal)
            imgRes = 0
        }
        iv_eat.setOnClickListener {
            selectNone(iv_eat)
            imgRes = 1
        }
        iv_gift.setOnClickListener {
            selectNone(iv_gift)
            imgRes = 2
        }
        iv_cake.setOnClickListener {
            selectNone(iv_cake)
            imgRes = 3
        }
        iv_idea.setOnClickListener {
            selectNone(iv_idea)
            imgRes = 4
        }
        cb_countDown.setOnCheckedChangeListener { _, b ->
            if (b) {
                countType = 0
                cb_countDown.isChecked = true
                cb_countUp.isChecked = false
                cb_week_tip.isEnabled = true
                cb_month_tip.isEnabled = true
            } else {
                countType = 1
                cb_countUp.isChecked = true
                cb_countDown.isChecked = false
                cb_week_tip.isEnabled = false
                cb_month_tip.isEnabled = false
                cb_week_tip.isChecked = false
                cb_month_tip.isChecked = false
            }
        }
        cb_countUp.setOnCheckedChangeListener { _, b ->
            if (b) {
                countType = 1
                cb_countUp.isChecked = true
                cb_countDown.isChecked = false
                cb_week_tip.isEnabled = false
                cb_month_tip.isEnabled = false
                cb_week_tip.isChecked = false
                cb_month_tip.isChecked = false
            } else {
                countType = 0
                cb_countDown.isChecked = true
                cb_countUp.isChecked = false
                cb_week_tip.isEnabled = true
                cb_month_tip.isEnabled = true
            }
        }
        cb_week_tip.setOnCheckedChangeListener { _, b ->
            if (b) {
                cb_month_tip.isChecked = false
            }
        }
        cb_month_tip.setOnCheckedChangeListener { _, b ->
            if (b) {
                cb_week_tip.isChecked = false
            }
        }
    }

    private fun selectNone(iv: AppCompatImageView) {
        iv_goal.setBackgroundResource(0)
        iv_eat.setBackgroundResource(0)
        iv_gift.setBackgroundResource(0)
        iv_cake.setBackgroundResource(0)
        iv_idea.setBackgroundResource(0)
        iv.setBackgroundResource(R.drawable.bg_corner)
    }

    private fun getById() {
        LitePal.findAsync(FlagBean::class.java, id).listen(object : FindCallback {
            override fun <T : Any?> onFinish(t: T) {
                bean = t as FlagBean
                setData(bean)
            }
        })
    }

    private fun setData(bean: FlagBean) {
        et_title.setText(bean.title)
        et_title.setSelection(bean.title.length)
        et_desc.setText(bean.desc)
        tv_date.text = bean.date
        imgRes = bean.imgRes
        when (imgRes) {
            0 -> {
                selectNone(iv_goal)
            }
            1 -> {
                selectNone(iv_eat)
            }
            2 -> {
                selectNone(iv_gift)
            }
            3 -> {
                selectNone(iv_cake)
            }
            4 -> {
                selectNone(iv_idea)
            }
        }
        countType = bean.countType
        if (countType == 1) {
            cb_countDown.isChecked = false
            cb_countUp.isChecked = true
            cb_week_tip.isEnabled = false
            cb_month_tip.isEnabled = false
        } else {
            cb_countDown.isChecked = true
            cb_countUp.isChecked = false
        }
        cb_week_tip.isChecked = bean.weekSchedule == 1
        cb_month_tip.isChecked = bean.monthSchedule == 1
    }

    private fun picker() {
        val dialog = AlertDialog.Builder(this).create()
        val calendar = Calendar.getInstance()
        val datapicker = DatePicker(this)
        dialog.show()
        datapicker.setDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1)
        datapicker.setMode(DPMode.SINGLE)
        datapicker.setOnDatePickedListener { date ->
            val data: Date
            try {
                data = sdf.parse(date)
                tv_date.text = sdf.format(data)
                dialog.dismiss()
            } catch (e: ParseException) {
                e.printStackTrace()
            }
        }
        val params = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        dialog.window!!.setContentView(datapicker, params)
        dialog.window!!.setGravity(Gravity.CENTER)
    }


    private fun save() {
        if (et_title.text.toString().trim().isEmpty()) {
            Toast.makeText(this@DetailActivity, "请输入主题", Toast.LENGTH_SHORT).show()
            return
        }
        if (tv_date.text.toString().trim().isEmpty()) {
            Toast.makeText(this@DetailActivity, "请选择日期", Toast.LENGTH_SHORT).show()
            return
        }
        if (id == -1L) {
            bean = FlagBean()
        }
        bean.title = et_title.text.toString().trim()
        bean.date = tv_date.text.toString()
        bean.desc = et_desc.text.toString().trim()
        bean.countType = countType
        bean.imgRes = imgRes
        //倒计时才有每周每月功能
        if (countType == 0) {
            if (cb_week_tip.isChecked) {
                bean.weekSchedule = 1
            } else {
                bean.weekSchedule = -1
            }
            if (cb_month_tip.isChecked) {
                bean.monthSchedule = 1
            } else {
                bean.monthSchedule = -1
            }
        } else {
            bean.weekSchedule = -1
            bean.monthSchedule = -1
        }
        val result = bean.save()
        if (result) {
            Toast.makeText(this@DetailActivity, "保存成功", Toast.LENGTH_SHORT).show()
            refreshData()
        } else {
            Toast.makeText(this@DetailActivity, "保存失败", Toast.LENGTH_SHORT).show()
        }
    }


    private fun refreshData() {
        FlagFm.instance?.initData()
        finish()
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when (item?.itemId) {
            android.R.id.home -> {
                onBackPressed()
                return true
            }
            R.id.action_done -> {
                save()
                return true
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.menu, menu)
        return true
    }
}
